# load data
rm(list = ls())
library(foreign)
library(tidyverse)
library(stargazer)
library(haven)
#Summary Stats of Individuals, T-test######
library(xtable)
library(tidyverse)
df = read_rds( "~/Dropbox/political_risk/replication_files/ind_summary_stats.rds") %>% 
  select(-personid)

# function of summary stats
treat = df %>% 
  filter(rd_official == 1) %>% 
  dplyr::select(-rd_official)

treat = map_df(treat, function(x) {
  tibble(N=length(na.omit(x)), Mean=mean(x,na.rm = T), `St. Dev.`=sd(x,na.rm = T))
})

control = df %>% 
  filter(rd_official == 0) %>% 
  select(-rd_official)

control = map_df(control, function(x) {
  tibble(N=length(na.omit(x)), Mean=mean(x,na.rm = T), `St. Dev.`=sd(x,na.rm = T))
})

# t-test
a = df %>%
  dplyr::select(-rd_official) %>% 
  map(~t.test(.x ~ df$rd_official, data = df)) 
a[[1]]$stderr
a %>% map("estimate") %>% map(2) %>% unlist()

vis = tibble(
  RD_Officials =  a %>% map("estimate") %>% map(2) %>% unlist() %>% round(3),
  Others = a %>% map("estimate") %>% map(1) %>% unlist()  %>% round(3),
  Dif =  a %>% map("estimate") %>% map(2) %>% unlist()  %>% round(3) -  a %>% map("estimate") %>% map(1) %>% unlist() %>% round(3),
  P_value =  a %>% map_dbl( "p.value") %>% round(3)
)  
vis

var_name = c("Female","Age","Years of Education", 
             "CPC Member","People Congress Member", 
             "CPPCC Member","Length of Tenure")

bind_cols(  Variable = var_name,
            treat,control,vis %>% select( Dif, P_value)
) %>%
  tibble() %>% 
  xtable()

#Table A2####
# Summary statistics####
final_df = read_dta("~/Dropbox/political_risk/replication_files/pc_df_2022test.dta")
final_df2012 = final_df  %>%  filter(year >2011)

final_df2012 %>%
  mutate(stloan_l = log(stloan+1),
         taxpay_l = log(taxpay+1),
         invinest_l = log(invinest+1)) %>% 
  as.data.frame()%>%
  select(roa,roe,profm,eps,pc_dummy, pc, cpc, npc, cppcc ,size,incmope_l, taxpay_l,invinest_l,stloan_l,n_positive_r,purge,purge_dummy,mkt_index) %>%
  stargazer( digits =2, 
             #type = "text", 
             covariate.labels = c("Returns on Asset (%)","Returns on Equity (%)", 
                                  "Profit Margin", "Earnings Per Share" ,"Revolving Door (binary)", 
                                  "Revolving Door (continuous)", "Communist Party Member", 
                                  "People's Congress Deputy", "People's Consultative Conference Member",
                                  "Firm Size (logged)", "Revenue (logged)", "Tax (logged)", 
                                  "Real Estate Investment", "Bank Loan (logged)","Investor Mentality",
                                  "Purge (Continuous)", "Purge (Dummy)","Market Development"))

